# encoding=utf-8
from gevent import monkey
monkey.patch_all()
import bottle
import pymongo
import datetime
import requests
from collections import Counter
from bottle import request, response, template
bottle.TEMPLATE_PATH.insert(0, "./static/")
app = application = bottle.Bottle()
db = pymongo.MongoClient(host="192.168.1.201").hackthon


def likely(a, b):
    try:
        seta = set(a)
        setb = set(b)
        like = len(seta & setb) * 1.0 / len(seta | setb)
        return like
    except:
        return 0.0


@app.get("/recommend/<login:path>")
def recommendpeople(login):
    result = db.most_common.find_one({"login": login})
    if result is None:
        return "no reuslt"
    login = result["login"]
    repos_map = {}
    login_repos = db.people_repolist.find_one({"login": login})
    if login_repos is not None:
        repos_map[login] = login_repos.get("repolist", [])

    most_common = result["most_common"]
    likely_map = {}

    if len(most_common) > 0:
        peoplelist = [x[0] for x in most_common]
        for people in peoplelist:
            tmp_result = db.people_repolist.find_one({"login": people})
            if tmp_result is not None:
                repos_map[people] = tmp_result.get("repolist", [])
            else:
                repos_map[people] = []

        for people in peoplelist:
            likely_map[people] = likely(repos_map.get(login, []), repos_map.get(people, []))
        # Get following
        s_likely_map = sorted(likely_map.items(), key=lambda x: x[1], reverse=True)
        print s_likely_map
        C = Counter()
        most_likely_people_list = [x[0] for x in s_likely_map]
        for people in most_likely_people_list[:5]:
            for i in repos_map.get(people, []):
                if i not in repos_map[login]:
                    C[i] += 1
        rec_repos = [x[0] for x in C.most_common(10)]
        return "\n".join(peoplelist + rec_repos)
    else:
        return "no people"


if __name__ == '__main__':
    bottle.run(app=app, host='0.0.0.0', port=8002)
